<?php


namespace App\Helpers;


use App\Models\ArticleCategory;
use App\Models\AuthorContributeStatistics;
use App\Models\AuthorSubmitStatistic;
use App\Models\Bill;
use App\Models\BillLog;
use App\Models\ConfigTable;
use App\Models\ContributeAuthor;
use App\Models\ContributeCategory;
use App\Models\ContributeConfig;
use App\Models\DepartmentContributeStatistics;
use App\Models\DepartmentMessageRecord;
use App\Models\DepartmentSubmitStatistic;
use App\Models\OnJobLog;
use App\Models\PerformanceTable;
use App\Models\Post;
use App\Models\ProvinceYearNews;
use App\Models\ProvinceYearRecord;
use App\Models\RecruitmentAuthor;
use App\Models\RecruitmentRegistration;
use App\Models\SystemUser;
use Illuminate\Support\Facades\DB;

trait StatisticsTrait
{
    //获取录用稿件所有作者关联信息
   protected function getRecordAuthor($request,$department_id){
       $from_year = $request->input('year','2022');
       $from_month = '01';
       $to_year = $request->input('year','2022');
       $to_month = $request->input('month',date('m'));
       //获取开始时间
       $from = $this->getSearchDate($from_year,$from_month);
       $to = $this->getSearchDate($to_year,$to_month);
      return RecruitmentAuthor::query()
           ->where('author_department_id',$department_id)
           ->whereBetween('created_at',[$from,$to])
           ->get();
   }

    //信息录用得分
    protected function getMessageRecordScores($id,$request,$number){
        //省级年度信息目标数
        $province_year_message = $this->getProvinceScoresComputed($id,$request);
        return round($number*$province_year_message);
    }
    protected function getNewsRecordScores($id,$request,$number){
        //省级年度新闻宣传目标数
       // $province_message_subject = $this->subject($id,2);
        //省级分数
        $province_year_message = $this->provinceScoresComputed($id,$request);
        return round($number*$province_year_message);
    }
    //省级信息录用分数换算
    protected function getProvinceScoresComputed($department_id){
       $value = ProvinceYearNews::query()->where('department_id',$department_id)
           ->where('year',$this->year)
           ->value('number');
       $score = ConfigTable::query()->where('key','province_year_record_score')->value('value');
       if($value){
           return $score/$value;
       }else{
           return 0;
       }
    }
    //省级宣传录用分数换算
    protected function provinceScoresComputed($department_id){
        $value = ProvinceYearRecord::query()->where('department_id',$department_id)
            ->where('year',$this->year)
            ->value('number');
        $score = ConfigTable::query()->where('key','province_year_record_score')->value('value');
        if($value){
            return $score/$value;
        }else{
            return 0;
        }
    }
    //换算分数
    protected function total($category_id){
       //获取篇数积分和比例系数
       $category =  ArticleCategory::query()->select('score','rate')->find($category_id);
       if(!$category){
           return 0;
       }
        return $category->score*$category->rate;
    }
    //获取所有信息录用稿件
    protected function allMessageRecord($data){
        $allScores = 0;
        foreach ($data as $k=>$v){
            if($v->author){
                $scores = 0;
                foreach($v->author as $m=>$n){
                    if($n->original_author==2){
                        $scores+=1;
                    }else{
                        $scores+=0.5;
                    }
                }
            }
            $allScores+=$v->rate*$scores;
        }
        return $allScores;
    }
    /**
     * 获取被录用人员
     */
    protected function getHiredAuthor(){
        return SystemUser::query()
            ->with('department')
            ->select('id','department_id','name','is_author')
//            ->where('is_author','>',1)
            ->orderByDesc('id')
            ->get();
    }
    /**
     * 上个月最后一天时间
     * @param $request
     * @return false|string
     */
    protected function getSearchDate($year,$month)
    {
        $accDate = $year.'-'.$month;
        $lastMonthLastDay = date("Y-m-d", strtotime("{$accDate} +1 month -1 day"));
        $times = $lastMonthLastDay.' 23:59:59';
        return $month = date('Y-m-d H:i:s',strtotime($times));
    }
    //个人报送数量
    protected function getSubmitted($author_id,$request){
        $from_year = $request->input('year','2022');
        $from_month = '01';
        $to_year = $request->input('year','2022');
        $to_month = $request->input('month',date('m'));
        //获取开始时间
        $from = $this->getSearchDate($from_year,$from_month);
        $to = $this->getSearchDate($to_year,$to_month);
        return RecruitmentAuthor::query()
            ->where('author_id',$author_id)
            ->whereBetween('created_at',[$from,$to])
            ->get();
    }
    //省级报送数量
    protected function getProvinceMessageSubmitted($author_id,$request){
        $from_year = $request->input('year','2022');
        $from_month = '01';
        $to_year = $request->input('year','2022');
        $to_month = $request->input('month',date('m'));
        //获取开始时间
        $from = $this->getSearchDate($from_year,$from_month);
        $to = $this->getSearchDate($to_year,$to_month);
        return RecruitmentAuthor::query()
            ->whereHas('recruitment',function($query){
            $query->where('first',1)->where('second',1);
        })
            ->where('author_id',$author_id)
            ->whereBetween('created_at',[$from,$to])
            ->get();
    }
    protected function getSubmittedScores($data){
        if(count($data)>0){
            $score = 0;
            foreach ($data as $k=>$v){
                if($v->is_co_editing==1){//合编
                    $score+=$this->coEditing($v);
                }else{
                    $score+= $this->total($v->last_category_id);
                }
            }
        }
        return $score;
    }
    //获取个人分数
    protected function coEditing($v){
        if($v){
            if($v->last_category_id){
                $category = ArticleCategory::query()->find($v->last_category_id);
                if(!$category){
                    return 0;
                }
                //获取作者人数
                $author_num = RecruitmentAuthor::query()
                    ->where('recruitment_id', $v->recruitment_id)->count();
                //规则
                return 0.5*$category->rate*$this->getPersonScores($category->score,$author_num);
//                if($v->first==1){
//                    return 0;
//                }else{
//                    return $category->rate*$this->getPersonScores($category->score,$author_num);
//                }
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
    protected function getPersonScores($score,$num){
        $sc = $score/$num;
        if($sc<0.2){
            return 0.2;
        }else{
            return $sc;
        }
    }

    //获取该稿件分类对应的分数
    protected function getContributeScore($contribute_id){
        $data = RecruitmentRegistration::query()
            ->with(['category'=>function($query){
                $query->select('id','score');
            }])
            ->select('id','rate')
            ->where('id',$contribute_id)
            ->first();
        if($data&&$data->catgory){
            return $data->rate*$data->category->score;
        }else{
            return 0;
        }
    }
    //获取作者投送数量
    //$type = 1 信息报送
    //$type = 2 外宣报送数量
    // status=2 已审核
    //
    protected function getPersonalSubmitedNum($author_id,$request,$category_id){
        $year = $request->input('year','2022');
        $month = $request->input('month',date('m'));
        //获取开始时间
        $from = $this->getSearchDate($year,$month);
        list($start,$end) = $this->getthemonth($from);
        $model =  AuthorSubmitStatistic::query()
            ->where('author_id',$author_id)
            ->whereBetween('created_at',[$start,$end]);
        if($category_id){
            $model = $model->where('category_id',$category_id);
        }
            return $model->count();
    }
    //获取某月开始和结束时间
    function getthemonth($date)
    {
        $firstday = date('Y-m-01 00:00:00', strtotime($date));
        $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
        return array($firstday, $lastday);
    }
    protected function getCurrently($department_id,$category_id=0){
        $month = '01';
        //获取开始时间
        $start = $this->getSearchDate($this->year,$month);
        $end = $this->getSearchDate($this->year,$this->month);
        //获取投稿数组
        return $this->getSubmitContribut($department_id,$start,$end,$category_id);
    }

    /**
     * @param $department_id
     * @param $start
     * @param $end
     * @return int
     * 根据条件获取报送篇数
     */
    protected function getSubmitContribut($department_id,$start,$end,$category_id=0){
        $arr = $this->getProvinceRecordArr();
        $model = DepartmentContributeStatistics::query()
            ->where('department_id',$department_id)
            ->whereIn('last_category_id',$arr)
            ->whereBetween('time',[strtotime($start),strtotime($end)]);

            if($category_id){
                $model = $model->where('category_id',$category_id);
            }
            $model = $model->get();
            $num = 0;
            foreach ($model as $k=>$v){
                if($v->is_co_editing==1){//合编
                    $n = 0.5*$this->getContributeCategoryRate($v->last_category_id);
                }else{
                    $n = $this->getContributeCategoryRate($v->last_category_id);
                }
                $num+=$n;
            }
            return $num;
    }
    protected function getProvinceRecordArr(){
        return ArticleCategory::query()->where('is_statistic',1)->pluck('id');
    }
    /**
     * 获取录用篇数系数
     */
    protected function getContributeCategoryRate($category_id){
        return ArticleCategory::query()->where('id',$category_id)->value('rate');
    }
    protected function getFinishContribue($id){
        $arr = $this->getProvinceRecordArr();
        $arr->push(21);

        return DepartmentContributeStatistics::query()
            ->where('department_id',$id)
            ->whereIn('last_category_id',$arr)->first();
    }
    //获取年度目标数
    protected function subject($department_id,$type=1){
        if($this->year){
            $year = $this->year;
        }else{
            $year = date('Y',time());
        }
        if($type==1){
            return ProvinceYearNews::query()->where('department_id',$department_id)
                ->where('year',$year)->value('number');
        }
        if($type==2){
            return ProvinceYearRecord::query()->where('department_id',$department_id)
                ->where('year',$year)->value('number');
        }

    }
    /**
     * 1.根据作者id 查找
     * 2.根据时间查找
     * 3.根据 类型查找
     * 4.根据级别查找
     */
    protected function recordScore($author_id,$request,$type=0,$level=0,$first=0){
        //获取开始时间
        $year = $request->input('year','2022');
        //获取开始时间
        $accMonth = date('m');
        $start = $this->getSearchDate($year,'01');
        $end =  $this->getSearchDate($year,$accMonth);
        $model = AuthorContributeStatistics::query();

        if($level==1){
            $model =  $model->whereHas('category',function($query){
                $query->where('is_statistic',1);
            });
        }

        if($first){
            $model = $model->where('first',$first);
        }
           $model=$model->where('author_id',$author_id)
            ->whereBetween('time',[strtotime($start),strtotime($end)]);
        $data = $model->get();

        if($type=='all'){
            return $data;
        }

        $num = 0;
        foreach ($data as $k=>$v){
            $rate = $this->getContributeCategoryRate($v->last_category_id);

            if($v->is_co_editing==1){//合编
                $n = 0.5*$rate;
            }else{
                $n = $rate;
            }
             $num+=$n;
        }
        return $num;

    }
    //根据条件获取月数任务数
    protected function getMonthTarget($id,$request){
        $month = $this->getMonth($request->month);
        return ContributeConfig::query()
            ->where('department_id',$id)
            ->value($month);
    }
    protected function getMonth($month){
        switch ($month){
            case 1:
                $result = 'jan';
                break;
            case 2:
                $result = 'feb';
                break;
            case 3:
                $result = 'mar';
                break;
            case 4:
                $result = 'apr';
                break;
            case 5:
                $result = 'may';
                break;
            case 6:
                $result = 'jun';
                break;
            case 7:
                $result = 'jul';
                break;
            case 8:
                $result = 'aug';
                break;
            case 9:
                $result = 'sep';
                break;
            case 10:
                $result = 'oct';
                break;
            case 11:
                $result = 'nov';
                break;
            case 12:
                $result = 'dec';
                break;
            default:
                $result = strtolower(date("M",time()));
                break;
        }
        return $result;
    }
    //X 月
    protected function getAccMonthTotal($department_id,$is_auth=null){
        list($start,$end) = $this->getthemonth(now());
        return $this->setDepartmentStatstic($department_id,$start,$end,$is_auth);
    }

    protected function departmentMonthTotal($department_id,$request,$is_auth=null){
        //获取开始时间 和 结束时间
        $year = $request->input('year','2022');
        $month = $request->input('month',date('m'));
        //获取开始时间
        $from = $this->getSearchDate($year,$month);
        list($start,$end) = $this->getthemonth($from);
        //获取投稿数组
        return $this->setDepartmentStatstic($department_id,$start,$end,$is_auth);
    }
    protected function setDepartmentStatstic($department_id,$start,$end,$is_author){
        $model = DepartmentSubmitStatistic::query()
                ->where('department_id',$department_id)
                ->whereBetween('created_at',[$start,$end]);
                if($is_author){
                    $model = $model->where('is_author',$is_author);

                }
        return $model->count();
    }
    /**
     * @param $data
     * 收稿管理
     */
    protected function setSubmitStatistic($data){
        DB::transaction(function ()use($data) {
            if($data->author){
                $department_arr = [];
                $author_arr = [];
                foreach($data->author as $k=>$v){
                    $category_id = $data->category->id;
                    //当前作者不重复
                    //if(!in_array($v->author_department_id,$department_arr)){
                        $departmentData['contribute_id'] = $v->contribute_id;
                        $departmentData['department_id'] = $v->author_department_id;
                        $departmentData['target'] = 1;
                        $departmentData['category_id'] = $category_id;
                        if($v->is_author==2){
                            $departmentData['is_author'] = $v->is_author;
                        }
                        DepartmentSubmitStatistic::query()->updateOrCreate($departmentData,['department_id'=>$v->author_department_id,'contribute_id'=>$v->contribute_id]);
                  //  }
                    $department_arr[] = $v->author_department_id;
                    $author_arr[$k]['contribute_id'] = $v->contribute_id;
                    $author_arr[$k]['author_id'] = $v->author_id;
                    $author_arr[$k]['category_id'] = $category_id;
                    $author_arr[$k]['created_at'] = now();
                    $author_arr[$k]['updated_at'] = now();
                }
                DB::table('author_submit_statistics')->insert($author_arr);
            }
        });
    }
}
